package com.budwk.app.sqfwV2.service.childrenVisitation;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.SummarySafetyCommponent;
import com.budwk.app.sqfwV2.dto.dto.childrenVisits.ChildrenVisitationPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.enums.FileServiceConfigEnum;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@IocBean
public class ChildrenVisitationServiceImpl implements ChildrenVisitationService {

    @Inject
    private ChildrenVisitationPdfService childrenVisitationPdfService;
    @Inject
    private ChildrenVisitationExcelService childrenVisitationExcelService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;

    @Override
    public void submitData(TemplateCodeUpdateDTO dto) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        // 组装参数
        CompleteFlowTemplateCodeUpdateDTO codeUpdateDTO = new CompleteFlowTemplateCodeUpdateDTO();
        codeUpdateDTO.setCompleteFlow(dto.getCompleteFlow());
        codeUpdateDTO.setFormSummary(dto.getFormSummary());
        param.setCompleteFlowDataDTO(codeUpdateDTO);
        param.setUserId(SecurityUtil.getUserId());

        // 初始创建任务
        summarySafetyCommponent.createOneTask(dto, null, SupportBusinessTypeEnum.CHILDREN_VISITATION.getName());
        childrenVisitationPdfService.createPdfAndMsg(param);
    }

    @Override
    public Result<?> reGeneratePDF(String sqfwFlowId) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        param.setCompleteFlowId(sqfwFlowId);
        childrenVisitationPdfService.reCreatePdfAndMsg(param);
        return Result.success();
    }

    @Override
    public Result<?> downExcelLedger(DownExcelLedgerReqVo reqVo) {
        List<Sqfw_formSummary_new> list = new ArrayList<>();
        if (CollectionUtil.isEmpty(reqVo.getSqfwIds())) {
            list = CommonComponent.querySummarys(null, SupportBusinessTypeEnum.CHILDREN_VISITATION.getName());
            if (CollectionUtil.isEmpty(list)) {
                return Result.success();
            }
            List<String> ids = list.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList());
            reqVo.setSqfwIds(ids);
        }
        List<ExcelCreateConfig> excelConfigList = CommonComponent.getExcelConfigList(reqVo);
        List<GenerateExcelUrlVO> result = childrenVisitationExcelService.downExcelLedger(reqVo, excelConfigList, SecurityUtil.getUserId(), list);
        return Result.data(result);
    }

    @Override
    public Result<?> listByConditionKey(String visitedName) {
        Criteria cri = Cnd.cri();
        if (StringUtils.isEmpty(visitedName)) {
            return Result.data(Lists.newArrayList());
        }
        // 1 组装查询条件
        SqlExpressionGroup criSql = cri.where();
        criSql.andEquals(Sqfw_formSummary_new::getType, SupportBusinessTypeEnum.CHILDREN_VISITATION.getName())
                .andEquals(Sqfw_formSummary_new::getUnitId, SecurityUtil.getUnitId());
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);

        // 自定义sql
        String sql = "param_data ->>'visitedName' like '%"+ visitedName +"%'";
        criSql.and(new Static(sql));
        // 2 查询数据
        List<Sqfw_formSummary_new> list = sqfwFormsummaryNewService.query(cri);
        if (list.size() == 0) {
            return Result.data(Lists.newArrayList());
        }
        // 3 对探访儿童姓名去重 取出最新的数据 返给前端
        List<Sqfw_formSummary_new> results = new ArrayList<>();
        List<String> voList = new ArrayList<>();
        for (Sqfw_formSummary_new formSummary : list) {
            ChildrenVisitationPdfDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), ChildrenVisitationPdfDTO.class);
            // 判断是否存在过
            long total = voList.stream().filter(e -> pdfDTO.getVisitedName().equals(e)).count();
            if (total > 0) {
                continue;
            }
            results.add(formSummary);
            voList.add(pdfDTO.getVisitedName());
        }
        return Result.data(results);
    }

    @Override
    public Result<List<DownFileTypesResVo>> listDownFileTypes(String sqfwId) {
        //2 按照社区服务id查询数据
        List<Sqfw_formSummary_new> list = null;
        if (StringUtils.isEmpty(sqfwId)) {
            list = CommonComponent.querySummarys(null, SupportBusinessTypeEnum.CHILDREN_VISITATION.getName());
        } else {
            list = sqfwFormsummaryNewService.queryBySqfwIdAndType(sqfwId, SupportBusinessTypeEnum.CHILDREN_VISITATION.getName());
        }
        // 检查数据是否可生成
        List<DownFileTypesResVo> results = new ArrayList<>();
        List<FileServiceConfigEnum> allExcel = FileServiceConfigEnum.findByFillType(SupportBusinessTypeEnum.CHILDREN_VISITATION.getName(), CommonConstants.EXCEL);
        for (FileServiceConfigEnum serviceConfig : allExcel) {
            getDownFileTypesResVo(results, list, serviceConfig);
        }
        List<FileServiceConfigEnum> allPdf = FileServiceConfigEnum.findByFillType(SupportBusinessTypeEnum.CHILDREN_VISITATION.getName(), CommonConstants.PDF);
        for (FileServiceConfigEnum fileEnum : allPdf) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setFileName(fileEnum.getLabel() + ".pdf").
                    setFileCode(fileEnum.getCode())
                    .setHiveData(list.size() > 0)
                    .setCreatedAt(System.currentTimeMillis())
                    .setFileType("pdf");
            results.add(resVo);
        }
        return Result.data(results);
    }

    @Override
    public void downWordTemplate(HttpServletResponse response) {
        String fileName = SupportBusinessTypeEnum.CHILDREN_VISITATION.getName() + ".docx";
        String filepath = CommonFormOfficeUtils.getTemplatePathByOS("sqfwV2/childrenVisits/template/childrenVisitsRecordWord.docx");
        // 下载文件
        CommonComponent.downFile(response, filepath, fileName);
    }

    private void getDownFileTypesResVo(List<DownFileTypesResVo> results, List<Sqfw_formSummary_new> list, FileServiceConfigEnum serviceConfig) {
        DownFileTypesResVo resVo = new DownFileTypesResVo();
        resVo.setFileCode(serviceConfig.getCode())
                .setFileName(serviceConfig.getFileName())
                .setHiveData(list.size() > 0)
                .setFileType("excel")
                .setLocation(serviceConfig.getLocation());
        results.add(resVo);
    }
}
